/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 * limitations under the License.
 */

package hadss.avoid_area.utils

import android.app.Activity
import android.content.Context
import android.graphics.Point
import android.view.View
import android.view.WindowManager

object AvoidAreaUtils {

    /**
     * 获取屏幕宽度
     */
    fun getScreenWidth(activity: Activity): Int {
        var windowManager: WindowManager =
            activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        var point = Point()
        windowManager.defaultDisplay.getRealSize(point)
        return point.x
    }

    /**
     * 获取屏幕高度
     */
    fun getScreenHeight(activity: Activity): Int {
        var windowManager: WindowManager =
            activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        var point = Point()
        windowManager.defaultDisplay.getRealSize(point)
        return point.y
    }

    /**
     * 获取顶部导航栏高度
     */
    fun getStatusBarHeight(activity: Activity): Int {
        var statusBarHeight = 0
        var resourceId = activity.resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            statusBarHeight = activity.resources.getDimensionPixelSize(resourceId)
        }
        return statusBarHeight
    }

    /**
     * 获取底部导航栏高度
     */
    fun getNavigationBarHeight(activity: Activity): Int {
        var navigationBarHeight = 0
        var resourceId =
            activity.resources.getIdentifier("navigation_bar_height", "dimen", "android")
        if (resourceId > 0) {
            navigationBarHeight = activity.resources.getDimensionPixelSize(resourceId)
        }
        return navigationBarHeight
    }

    fun isNavigationBarVisible(activity: Activity): Boolean {
        var uiOptions = activity.window.decorView.systemUiVisibility
        var isFullScreen = (uiOptions and View.SYSTEM_UI_FLAG_FULLSCREEN) != 0
        var isImmersiveMode = (uiOptions and View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0
        return !isFullScreen && !isImmersiveMode && isNavigationBarPresent(activity)
    }

    fun isNavigationBarPresent(activity: Activity): Boolean {
        var rect = android.graphics.Rect()
        activity.window.decorView.getWindowVisibleDisplayFrame(rect)
        var screenHeight = getScreenHeight(activity)
        var usableHeight = rect.height()
        return screenHeight > usableHeight
    }
}